Day 5 - Semicolon, logical AND, pipes
22
So far, when we run commands the output was printed (magically?) on the terminal, and that’s fine,
as most of the time we want to see what a command does. The input of the commands, on the other
hand, came almost exclusively from files that are already on your hard disk. What happens you you
run
$ head -n 10 slices.txt | tail -n 5
If your system doesn’t have the hiccup you should see the lines from 6 to 10 of the slices.txt file.
But, but… we asked head to show us 10 lines, this is definitely fishy. The | operator is called pipe
and its effect is that of piping the output of the first command, preventing it to reach the terminal,
and instead going directly into the tail -n 5 command. So we got the last 5 lines of the first 10
lines of slices.txt, that is lines from 6 to 10.
I told you this lesson was about plumbing.
Many Unix commands that work on files accept input from a pipe instead, and you might see now
why this is so important. Through pipes you can connect commands, creating your own complex
operators from simpler ones.
And now, welcome to the Operating Systems Philosophy class of professor Unix! I’m only half
joking here, the so-called Unix philosophy dictates that you should provide small programs that do
a very specific things, and that do it at their best. You will then compose them with pipes and other
operators to create more complex programs.
Caveat You will notice that later in the book I always use the pattern cat <file> | <command>,
even though the man page of many commands shows that you might as well run <command> <file>
omitting the cat and the pipe. While I use both versions in my daily tasks, I preferred the first one
in this book because it makes clearer what the <command> does, and it helps familiarising with pipes.
Enough for today! You will probably have nightmares about leaky pipes, philosophers and Pharaohs.
I can only recommend a good book and a cup of tea. Just don’t read anything related to ancient
cultures!
Suggested film for the evening: Stargate (1997) - Some Unix programmers work together on a
manufact that apparently shows that ancient Egyptians were familiar with the command line.